//basic
function _g(id){
  return document.getElementById(id);
}
function _gn(a){
  return document.getElementsByName(a);
}
function _unesc(a) {
  return window.decodeURIComponent ? decodeURIComponent(a) : unescape(a)
}
function _type(value) {
  var s = typeof value;
  if (s == 'object') {
    if (value) {
      // We cannot use constructor == Array or instanceof Array because
      // different frames have different Array objects. In IE6, if the iframe
      // where the array was created is destroyed, the array loses its
      // prototype. Then dereferencing val.splice here throws an exception, so
      // we can't use goog.isFunction. Calling typeof directly returns 'unknown'
      // so that will work. In this case, this function will return false and
      // most array functions will still work because the array is still
      // array-like (supports length and []) even though it has lost its
      // prototype.
      // Mark Miller noticed that Object.prototype.toString
      // allows access to the unforgeable [[Class]] property.
      //  15.2.4.2 Object.prototype.toString ( )
      //  When the toString method is called, the following steps are taken:
      //      1. Get the [[Class]] property of this object.
      //      2. Compute a string value by concatenating the three strings
      //         "[object ", Result(1), and "]".
      //      3. Return Result(2).
      // and this behavior survives the destruction of the execution context.
      if (value instanceof Array ||  // Works quickly in same execution context.
          // If value is from a different execution context then
          // !(value instanceof Object), which lets us early out in the common
          // case when value is from the same context but not an array.
          // The {if (value)} check above means we don't have to worry about
          // undefined behavior of Object.prototype.toString on null/undefined.
          //
          // HACK: In order to use an Object prototype method on the arbitrary
          //   value, the compiler requires the value be cast to type Object,
          //   even though the ECMA spec explicitly allows it.
          (!(value instanceof Object) &&
           (Object.prototype.toString.call(
               /** @type {Object} */ (value)) == '[object Array]') ||

           // In IE all non value types are wrapped as objects across window
           // boundaries (not iframe though) so we have to do object detection
           // for this edge case
           typeof value.length == 'number' &&
           typeof value.splice != 'undefined' &&
           typeof value.propertyIsEnumerable != 'undefined' &&
           !value.propertyIsEnumerable('splice')

          )) {
        return 'array';
      }
      // HACK: There is still an array case that fails.
      //     function ArrayImpostor() {}
      //     ArrayImpostor.prototype = [];
      //     var impostor = new ArrayImpostor;
      // this can be fixed by getting rid of the fast path
      // (value instanceof Array) and solely relying on
      // (value && Object.prototype.toString.vall(value) === '[object Array]')
      // but that would require many more function calls and is not warranted
      // unless closure code is receiving objects from untrusted sources.

      // IE in cross-window calls does not correctly marshal the function type
      // (it appears just as an object) so we cannot use just typeof val ==
      // 'function'. However, if the object has a call property, it is a
      // function.
      if (!(value instanceof Object) &&
          (Object.prototype.toString.call(
              /** @type {Object} */ (value)) == '[object Function]' ||
          typeof value.call != 'undefined' &&
          typeof value.propertyIsEnumerable != 'undefined' &&
          !value.propertyIsEnumerable('call'))) {
        return 'function';
      }


    } else {
      return 'null';
    }

  } else if (s == 'function' && typeof value.call == 'undefined') {
    // In Safari typeof nodeList returns 'function', and on Firefox
    // typeof behaves similarly for HTML{Applet,Embed,Object}Elements
    // and RegExps.  We would like to return object for those and we can
    // detect an invalid function by making sure that the function
    // object has a call method.
    return 'object';
  }
  return s;
};
function arrayIndexOf(arr, obj, opt_fromIndex){
      var fromIndex = opt_fromIndex == null ?
          0 : (opt_fromIndex < 0 ?
               Math.max(0, arr.length + opt_fromIndex) : opt_fromIndex);

      for (var i = fromIndex; i < arr.length; i++) {
        if (i in arr && arr[i] === obj)
          return i;
      }
      return -1;
}
function getElementsByClass(elementClass, context){
  if(elementClass == null){
    alert("element class is null.");
    return null;
  }
  if(context == null) context = document;
  
  var els = context.getElementsByTagName('input' || '*');

  if (elementClass) {
    var arrayLike = {};
    var len = 0;
    for (var i = 0, el; el = els[i]; i++) {
      var className = el.className;
      // Check if className has a split function since SVG className does not.
      if (typeof className.split == 'function' &&
          arrayIndexOf(className.split(/\s+/), elementClass) > -1) {
        arrayLike[len++] = el;
      }
      
    }
    arrayLike.length = len;
    return arrayLike;
  } else {
    return els;
  }
}
function _get(elementClass, context){
  var els = getElementsByClass(elementClass, context);
  return (els && els.length > -1) ? els[0] : null;
}
function getElementsByNameLike(name, opt_tag, opt_el) {
  var parent = opt_el || document;
  var tagName = (opt_tag && opt_tag != '*') ? opt_tag.toUpperCase() : '';
  var els = parent.getElementsByTagName(tagName || '*');
  var arrayLike = {};
  var len = 0;
  for(var i = 0, el;el = els[i]; i++){
   if(el.name &&  new RegExp(name).test(el.name))
    arrayLike[len++] = el;
  }
  return arrayLike;
}

//form
function getParentForm(node) {
  var found = false;
  while (!found) {
    if(node == null) return null;
      if (node.nodeName == 'FORM') {
          found = true;
          return node;
      }
      node = node.parentNode;
  }
  return null;
}
function getPageHtml(currentNode){
  var pageHtml = {};
  var parentForm = getParentForm(currentNode);
  if(!parentForm){
    alert("cannot find parent form.");
    return false;
  }
  var eOrderBy = _get("orderBy", parentForm);
  var eOrder = _get("order", parentForm);
  var ePageNo = _get("pageNo", parentForm);
  if(!eOrderBy || !eOrder || !ePageNo){
    alert("cannot find orderBy or order or pageNo element.");
    return false;
  }
  pageHtml.form = parentForm;
  pageHtml.orderBy = eOrderBy;
  pageHtml.order = eOrder;
  pageHtml.pageNo = ePageNo;
  return pageHtml;
}
function jumpPage(pageNo, currentNode) {
  var pageHtml = getPageHtml(currentNode);
  if(!pageHtml) return false;
  
  pageHtml.pageNo.value = pageNo;
  pageHtml.form.submit();
}
function sort(orderBy, currentNode) {
  var pageHtml = getPageHtml(currentNode);
  if(!pageHtml) return false;
  if (pageHtml.orderBy.value == orderBy) {
    if (pageHtml.order.value == "") {
      pageHtml.order.value = "asc";
    }
    else if (pageHtml.order.value == "desc") {
      pageHtml.order.value = "";
    }
    else if (pageHtml.order.value == "asc") {
      pageHtml.order.value = "desc";
    }
  }
  else {
    pageHtml.orderBy.value = orderBy;
    pageHtml.order.value = "asc";
  }

  pageHtml.form.submit();
}

function search(currentNode) {
  var pageHtml = getPageHtml(currentNode);
  if(!pageHtml) return false;
  pageHtml.orderBy.value = "";
  pageHtml.order.value = "";
  pageHtml.pageNo.value = "1";

  pageHtml.form.submit();
}

function submitMethod(method, formId){
  if(formId == null) formId = "mainForm"; 
  var f = _g(formId);
  if(!f){
    alert("cannot find form "+formId+".");
    return false;
  }
  var eMethod = _get("method", f);
  if(!eMethod){
    alert("cannot find method element.");
    return false;
  }
  eMethod.value=method;
  f.submit();
}



//dropdown
function showDropDown(data,codeElementName,dropPrefix,defaultOption){
  for(var i=0;i<codeElementName.length;i++)
    showx(i,data,codeElementName,dropPrefix,defaultOption);
}
  
function equalInnerHTML(html,callback){
  var f = document.createDocumentFragment();
  var isTable = html.indexOf("<tbody") > -1;
  //var d = isTable?document.createElement("table"):document.createElement("div");
  var d = document.createElement("div");
  //if(isTable) alert(d.outerHTML);
  d.innerHTML = html;
  (function(){
    if(d.firstChild){
      f.appendChild(d.firstChild);
      setTimeout(arguments.callee,0)
    }else{
      if(isTable)
        callback(f.firstChild.firstChild);
      else
        callback(f.firstChild);
    }
  })()
}
function findSubList(data,value){
  var list = [];
  if(data == null) return list;
  for(var i =0; i < data.length;i++){
    if(data[i].code == value)
       list = data[i].list;
  }
  return list;
}

function getDataByGrade(x,data,codeElementName){
  var list = data;
  if(list == null) list = [];
  for(var i = 0;i<x&&list&&list.length>0;i++){
    list = findSubList(list,_gn(codeElementName[i])[0].value)
  }
  return list;
}

function showx(x,data,codeElementName,dropPrefix,defaultOption){
  if(dropPrefix == null ) dropPrefix = "drop";
  if(defaultOption == null ) defaultOption = '<option value="">&#35831;&#36873;&#25321;</option>';
  var containerPrefix = dropPrefix + "Container";
  var list = getDataByGrade(x,data,codeElementName);
  //if(x==2) alert(list);
  var newSelect = '<select id="'+dropPrefix+'_'+x+'">'+defaultOption;
  for(var i =0; list && i < list.length;i++){
    newSelect +='<option value="'+list[i]["code"]+'"'
    +(_gn(codeElementName[x])[0].value + "" == list[i]["code"]?' selected':"")
    +'>'+list[i]["name"]+'</option>'; 
  }
  newSelect += '</select>';
  _g(containerPrefix+"_"+x).removeChild(_g(dropPrefix+"_"+x));
  equalInnerHTML(newSelect,function(f){
    _g(containerPrefix+"_"+x).appendChild(f);
    _g(dropPrefix+"_"+x).onchange=function(event){
      var drop = (window.event && window.event.srcElement) ? window.event.srcElement : event.target;
      var num = parseInt(drop.id.substring(dropPrefix.length + 1));
      _gn(codeElementName[num])[0].value = drop.options[drop.selectedIndex].value;
      for(var j = num+1;j<codeElementName.length;j++){
        _gn(codeElementName[j])[0].value = "";
      }
      for(var k = num+1;k<codeElementName.length;k++){
        showx(k,data,codeElementName,dropPrefix,defaultOption);
      }
    }
  })
}
//ajax  
function _trim( text ) {
  return (text || "").replace( /^\s+|\s+$/g, "" );
}
function _e(s) {
  return escape(escape(s));
}
function now(){
  return +new Date;
}
function _ajax(url,process){
  var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
/*    */
  try {
    //xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  } catch(e){}
  var ts = now();
  // try replacing _= if it is there
  var ret = url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
  // if nothing was replaced, add timestamp to the end
  url = ret + ((ret == url) ? (url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
//url = encodeURI(url);
  xhr.open("GET", url, true);
  xhr.onreadystatechange = function(){
    if(xhr.readyState==4){
      process(xhr);
    }
  }
  xhr.setRequestHeader( "Content-Type", "text/html;charset=GBK" );
  xhr.send(null);
}
function bindSelect(selectId,inputId){
  var selectElement = _g(selectId);
  var inputElement = _g(inputId);
  var x = (inputElement && inputElement.value) ? inputElement.value : null;
  var os = selectElement.options;
  if(x && os && os.length)
    for(var i = 0;i< os.length;i++){
      if(os[i].value == x) os[i].selected = true;
    }
  selectElement.onchange = function(){
    inputElement.value = os[selectElement.selectedIndex].value;
  }
}


function refreshMessageJsonString(jsonString){
	return refreshMessage(JSON.parse(jsonString));
}

function refreshMessage(json,clear){
	if(clear == null) clear = true;
	var isOk = true;
	var m = json;
	var html = "";
	if(clear){
		_g("messageContainer").innerHTML = "";
		_g("errorContainer").innerHTML = "";
	}
	if(m && m.message){
		_g("messageContainer").innerHTML = "";
		if(_type(m.message) == 'array'){
			for(var i = 0; i<m.message.length;i++){
				html = '<div class="message">' + m.message[i] + '</div>';
				equalInnerHTML(html,function(h){
					_g("messageContainer").appendChild(h);
				})
			}
		}else{
			html = '<div class="message">' + m.message + '</div>';
			equalInnerHTML(html,function(h){
				_g("messageContainer").appendChild(h);
			})
		}
	}
	if(m && m.error){
		_g("errorContainer").innerHTML = "";
		isOk = false;
		if(_type(m.error) == 'array'){
			for(var i = 0; i<m.error.length;i++){
				html = '<div class="error">' + m.error[i] + '</div>';
				equalInnerHTML(html,function(h){
					_g("errorContainer").appendChild(h);
				})
			}
		}else{
			html = '<div class="error">' + m.error + '</div>';
			equalInnerHTML(html,function(h){
				_g("errorContainer").appendChild(h);
			})
		}
	}
	return isOk;
}
